use std::fmt::Debug;
use serde::Serialize;
use crate::extends::core::db::data_converter::DataConverter;

/// 更新语句构造器
pub struct UpdateBuilder;

impl UpdateBuilder {
    /// 构建更新语句
    ///
    /// # 参数
    /// * `table_name` - 表名
    /// * `data` - 要更新的数据，必须实现 `Sized`、`Debug` 和 `Serialize` 特性
    /// * `conditions` - 更新条件
    ///
    /// # 返回值
    /// 返回一个包含更新语句的字符串
    pub fn build<T>(table_name: &str, data: &T, conditions: &str) -> String
        where
            T: Sized + Debug + Serialize,
    {
        // 将数据转换为哈希映射
        let data_map = DataConverter::convert_to_map(data, true);
        let mut fields = vec![];

        // 过滤掉 id 字段
        for (key, value) in data_map {
            if key != "id" {
                fields.push(format!("{} = {}", key, value));
            }
        }

        // 生成更新语句
        format!(
            "UPDATE {} SET {} WHERE {}",
            table_name,
            fields.join(", "),
            conditions
        )
    }
}



fn main() {
    #[derive(Debug, Serialize)]
    struct User {
        id: Option<String>,
        email: Option<String>,
        first_name: Option<String>,
        last_name: Option<String>,
        username: Option<String>,
    }

    let user = User {
        id: Some("1".to_string()),
        email: Some("test@example.com".to_string()),
        first_name: Some("John".to_string()),
        last_name: Some("Doe".to_string()),
        username: Some("johndoe".to_string()),
    };


    let update_sql = UpdateBuilder::build("users", &user, "id = 1");
    log::info!("{}", update_sql);
}
